package com.aaron.gesturehelper;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.gesture.Gesture;
import android.gesture.GestureLibraries;
import android.gesture.GestureLibrary;
import android.gesture.GestureOverlayView;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class GestureBuilder extends Activity implements OnItemClickListener {
	
	private ListView mView;
	private String[] mGestureNamesInLib;
	private String[] mGestureNames;
	private GestureDialog mDefineDialog;
	private GestureLibrary mLibrary;
		
	private MyAdapter mAdapter; 
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.gesturebuilder);
		mView = (ListView) findViewById(R.id.list);
		mGestureNames = getResources().getStringArray(R.array.GESTURES);
		mGestureNamesInLib = getResources().getStringArray(R.array.GESTURESNAMES);
		HashMap<String,Bitmap> map = loadGesture();
		
		mAdapter = new MyAdapter(this,map);
		mView.setAdapter(mAdapter);
		mView.setOnItemClickListener(this);
		
		mDefineDialog = new GestureDialog(this);
	}
	
	public void onResume() {
		super.onResume();
		showTips();
	}
	
	private void showTips() {
		if(!MyConfiguration.getInstance(this).getBoolean(MyConfiguration.TIPS, false)) {
			AlertDialog.Builder build = new AlertDialog.Builder(this);
			build.setTitle(R.string.gesturebuilder).setMessage(R.string.gesturetips).setPositiveButton(android.R.string.ok, null).show();
			MyConfiguration.getInstance(this).setBoolean(MyConfiguration.TIPS, true);
		}
	}
	
	private HashMap<String,Bitmap> loadGesture() {
		mLibrary = GestureLibraries.fromFile(new File(getFilesDir(),"mygestures"));
		HashMap<String,Bitmap> map = new HashMap<String, Bitmap>();
		if (mLibrary.load()) {
            for (String name : mLibrary.getGestureEntries()) {
                for (Gesture gesture : mLibrary.getGestures(name)) {
                    final Bitmap bitmap = gesture.toBitmap(64, 64, 8, Color.YELLOW);
                    map.put(name, bitmap);
                }
            }
        }
		return map;
	}
	
	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		mDefineDialog.setDialogId(position);
		String define = getResources().getString(R.string.define);
		mDefineDialog.setTitle(define+" "+mGestureNames[position]);
		mDefineDialog.show();
		mDefineDialog.mGesture = null;
	}
	
	private class GestureDialog extends AlertDialog {

		private int mDialogId;
		private Gesture mGesture;
		
		private OnClickListener mListener = new OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				if (which == AlertDialog.BUTTON_POSITIVE) {
					ArrayList<Gesture> list = mLibrary.getGestures(mGestureNamesInLib[mDialogId]);
					if(list != null) {
						for (Gesture gesture :list) {
							mLibrary.removeGesture(mGestureNamesInLib[mDialogId], gesture);
						}
					}
					if (mGesture != null) {
						mLibrary.addGesture(mGestureNamesInLib[mDialogId], mGesture);
						mAdapter.getGestureLib().put(mGestureNamesInLib[mDialogId],mGesture.toBitmap(64, 64, 8, Color.YELLOW));
						mAdapter.notifyDataSetChanged();
					} else {
						mAdapter.getGestureLib().remove(mGestureNamesInLib[mDialogId]);
						mAdapter.notifyDataSetChanged();
					}
					mLibrary.save();
					Intent intent = new Intent(Contants.INTENT_CONFIGURATION_CHANGED);
					intent.putExtra(MyConfiguration.GESTURE, true);
					sendBroadcast(intent);
				}
			}
		};
		
		private class GesturesProcessor implements GestureOverlayView.OnGestureListener {
	        public void onGestureStarted(GestureOverlayView overlay, MotionEvent event) {
	            mGesture = null;
	        }

	        public void onGesture(GestureOverlayView overlay, MotionEvent event) {
	        }

	        public void onGestureEnded(GestureOverlayView overlay, MotionEvent event) {
	            mGesture = overlay.getGesture();
	            if (mGesture.getLength() < 120) {
	                overlay.clear(false);
	                mGesture = null;
	            }
	        }

	        public void onGestureCancelled(GestureOverlayView overlay, MotionEvent event) {
	        }
	    }
		
		protected GestureDialog(Context context) {
			super(context);
			View v = LayoutInflater.from(context).inflate(R.layout.gesturearea, null);
			GestureOverlayView gesture = (GestureOverlayView) v.findViewById(R.id.gestures_overlay);
			gesture.addOnGestureListener(new GesturesProcessor());
			setView(v);
			setButton(AlertDialog.BUTTON_POSITIVE, context.getString(android.R.string.ok), mListener);
			setButton(AlertDialog.BUTTON_NEGATIVE, context.getString(android.R.string.cancel), mListener);
		}
		
		public void setDialogId(int id) {
			mDialogId = id;
		}
	}
	
	private class MyAdapter extends BaseAdapter {

		private HashMap<String,Bitmap> mGestureLib;
		private LayoutInflater mInflater;
		
		public MyAdapter(Context context, HashMap<String,Bitmap> map) {
			mInflater = LayoutInflater.from(context);
			mGestureLib = map;
		}
		
		public HashMap<String,Bitmap> getGestureLib() {
			return mGestureLib;
		}
		
		@Override
		public int getCount() {
			return mGestureNames.length;
		}

		@Override
		public Object getItem(int position) {
			return position;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if(convertView == null) {
				convertView = mInflater.inflate(R.layout.gestureitem, null);
			}
			TextView text = (TextView) convertView.findViewById(R.id.name);
			text.setText(mGestureNames[position]);
			
			ImageView image = (ImageView) convertView.findViewById(R.id.image);
			if(mGestureLib != null) {
				image.setImageBitmap(mGestureLib.get(mGestureNamesInLib[position]));
			}
			return convertView;
		}
	}
}
